package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.MainZuixinData;
import com.xindaoapp.happypet.bean.MainZuixinData.MainTiezi;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.MoccaPreferences;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.RollViewPager;

/**
 * 首页_最新+好友
 * 
 * @author Stone
 * 
 */
public class ZuiXinFragment extends BaseFragment {

    public static Fragment newInstance(boolean isZuixin) {
        Fragment fragment = new ZuiXinFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(Constants.KEY_IS_CLICK_TO_BACK, isZuixin);
        fragment.setArguments(bundle);
        return fragment;
    }

    private PullToRefreshListView mPullToRefreshListView;
    private ZuiXinAdapter mAdapter;

    private boolean mIsZuixin;
    private final boolean mFrist = true;
    private LoginSuccessReceiver mLoginSuccessReceiver;
    private ImageView mBackToTop;
    private Button bt_login;
    private View nologin;
    /** 轮播图 */
    private View mHeadView;
    private LinearLayout mViewPagerContainer;
    private TextView mTvDescription;
    private LinearLayout mPointsContainer;
    private List<HomeBanner> mBanners;
    private ArrayList<View> mDotLists;
    private RollViewPager mRollViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.zuixinfragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    protected void initViews() {
        // TODO Auto-generated method stub
        super.initViews();

        mBackToTop = (ImageView) mView.findViewById(R.id.iv_back_top);

        mIsZuixin = getArguments().getBoolean(Constants.KEY_IS_CLICK_TO_BACK);
        mPullToRefreshListView = (PullToRefreshListView) mView.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);

        bt_login = (Button) mView.findViewById(R.id.bt_gologin);
        nologin = mView.findViewById(R.id.nologin);

        mHeadView = LayoutInflater.from(mContext).inflate(R.layout.head_zuixinfragment, null);
        mViewPagerContainer = (LinearLayout) mHeadView.findViewById(R.id.viewpager1);
        mViewPagerContainer.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth * 248 / 640));
        mTvDescription = (TextView) mHeadView.findViewById(R.id.tv_image_description1);
        mPointsContainer = (LinearLayout) mHeadView.findViewById(R.id.ll_points1);

        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadDatas();
            }
        });

        mPullToRefreshListView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (firstVisibleItem >= 10) {
                    mBackToTop.setVisibility(View.VISIBLE);
                } else {
                    mBackToTop.setVisibility(View.GONE);
                }
            }
        });

        mBackToTop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPullToRefreshListView.getRefreshableView().setSelection(0);
            }
        });

        bt_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (UserState.isLogged(getActivity())) {

                }
            }
        });

        nologin.setOnClickListener(null);


    }

    @Override
    protected void initEvents() {
        // TODO Auto-generated method stub
        super.initEvents();
        mLoginSuccessReceiver = new LoginSuccessReceiver();
        mContext.registerReceiver(mLoginSuccessReceiver, new IntentFilter(
                Constants.ACTION_LOGIN_STATE_CHANGED));
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        getActivity().unregisterReceiver(mLoginSuccessReceiver);
    }

    @Override
    protected void loadDatas() {
        super.loadDatas();
        if (mIsZuixin) {
            nologin.setVisibility(View.GONE);
            getBannerData();
            getData();
        } else {
            nologin.setVisibility(View.VISIBLE);
            getBannerData2();
            getData2();
        }
    }

    private void getData2() {
        // TODO Auto-generated method stub
        if (UserState.getUser() != null) {
            nologin.setVisibility(View.GONE);
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getMainFriendData(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                            new IRequest<MainZuixinData>() {

                                @Override
                                public void request(MainZuixinData t) {

                                    if (null != t) {
                                        onDataArrived(true);
                                        if (t.array.size() == 0) {
                                            onDataArrivedEmpty();
                                        } else {
                                            MoccaPreferences.HaoYouTid.put(t.array.get(0).tid);
                                            mAdapter =
                                                    new ZuiXinAdapter(getActivity(), t.array,
                                                            Constants.PAGE_SIZE,
                                                            R.layout.item_zuixinfragment,
                                                            R.layout.item_loading);
                                            mPullToRefreshListView.setAdapter(mAdapter);
                                        }
                                    } else {
                                        onDataArrived(false);
                                    }
                                    mPullToRefreshListView.onRefreshComplete();
                                }
                            });
        } else {
            // 展示未登陆页面

            nologin.setVisibility(View.VISIBLE);

        }

    }

    private void getBannerData2() {
        // TODO Auto-generated method stub


        getMoccaApi().getIndexBanner("group", new IRequest<HomeBannerEntity>() {
            // getMoccaApi().getIndexBanner("index", new IRequest<HomeBannerEntity>() {
            @Override
            public void request(HomeBannerEntity t) {

                if (null != t) {
                    // onDataArrived(true);
                    if (t.getArray().size() == 0) {
                        // onDataArrivedEmpty();
                    } else {
                        mBanners = t.getArray();
                        prepareViewPage(mContext, mBanners);
                    }
                } else {
                    // onDataArrived(false);
                }
                // mPullToRefreshListView.onRefreshComplete();

            }
        });

    }

    private void getBannerData() {

        // getMoccaApi().getIndexBanner("group", new IRequest<HomeBannerEntity>() {
        getMoccaApi().getIndexBanner("index", new IRequest<HomeBannerEntity>() {
            @Override
            public void request(HomeBannerEntity t) {

                if (null != t) {
                    // onDataArrived(true);
                    if (t.getArray().size() == 0) {
                        // onDataArrivedEmpty();
                    } else {
                        mBanners = t.getArray();
                        prepareViewPage(mContext, mBanners);
                    }
                } else {
                    // onDataArrived(false);
                }
                // mPullToRefreshListView.onRefreshComplete();

            }
        });
    }

    public void prepareViewPage(final Context context, final List<HomeBanner> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        mRollViewPager =
                new RollViewPager(context, mDotLists, R.drawable.banner_normal,
                        R.drawable.banner_selected, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra(Constants.KEY_POST_TID,
                                            list.get(position % list.size()).getLink());
                                    context.startActivity(intent2);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                }
                            }
                        });
        mRollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        mRollViewPager.setTitle(mTvDescription, titleList);
        mRollViewPager.setImageUrl(imageUrlList);
        mRollViewPager.startRoll();
        mViewPagerContainer.removeAllViews();
        mViewPagerContainer.addView(mRollViewPager);

        if (list.size() > 0
                && mPullToRefreshListView.getRefreshableView().getHeaderViewsCount() <= 1) {
            mPullToRefreshListView.getRefreshableView().addHeaderView(mHeadView);
            mPullToRefreshListView.getRefreshableView().setAdapter(mAdapter);
        }

    }

    private void initDots(int size) {
        mDotLists = new ArrayList<View>();
        mPointsContainer.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext, 5),
                            CommonUtil.dip2px(mContext, 5));
            layoutParams.setMargins(5, 0, 5, 8);
            ImageView m = new ImageView(mContext);
            if (i == 0) {
                m.setBackgroundResource(R.drawable.banner_selected);
            } else {
                m.setBackgroundResource(R.drawable.banner_normal);
            }
            m.setLayoutParams(layoutParams);
            mDotLists.add(m);
            mPointsContainer.addView(m);
        }
    }

    private void getData() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getMainZuixinData(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                        new IRequest<MainZuixinData>() {

                            @Override
                            public void request(MainZuixinData t) {

                                if (null != t) {
                                    onDataArrived(true);
                                    if (t.array.size() == 0) {
                                        onDataArrivedEmpty();
                                    } else {
                                        mAdapter =
                                                new ZuiXinAdapter(getActivity(), t.array,
                                                        Constants.PAGE_SIZE,
                                                        R.layout.item_zuixinfragment,
                                                        R.layout.item_loading);
                                        mPullToRefreshListView.setAdapter(mAdapter);
                                    }
                                } else {
                                    onDataArrived(false);
                                }
                                mPullToRefreshListView.onRefreshComplete();
                            }
                        });
    }

    /**
     * 最新的适配器
     * 
     * @author Stone
     * 
     */

    class ZuiXinAdapter extends XinDaoBaseAdapter<MainZuixinData.MainTiezi> {
        Map<Integer, ImageView> map = new HashMap<Integer, ImageView>();
        Map<Integer, Boolean> isZanMap = new HashMap<Integer, Boolean>();
        Map<Integer, Boolean> isImgsMap = new HashMap<Integer, Boolean>();

        private int selectedposition1;
        private MainZuixinData.MainTiezi value1;
        private ViewHolder holder1;
        private List<MainTiezi> lisTiezis;

        public ZuiXinAdapter(Context context, List<MainZuixinData.MainTiezi> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        protected List<MainTiezi> parseResult(List<MainTiezi> list) {
            // TODO Auto-generated method stub
            lisTiezis = mAdapter.getResult();
            for (int i = list.size() - 1; i >= 0; i--) {
                if (lisTiezis.contains(list.get(i))) {
                    list.remove(list.get(i));
                }
            }
            return list;
        }

        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<MainZuixinData.MainTiezi> iLoadNextPageData) {
            super.nextPage(start, size, iLoadNextPageData);
            if (mIsZuixin) {
                HappyPetApplication.get().getMoccaApi()
                        .getMainZuixinData(start, size, new IRequest<MainZuixinData>() {

                            @Override
                            public void request(MainZuixinData t) {
                                iLoadNextPageData.loadNextPageData(t == null ? null : t.array);

                            }
                        });
            } else {
                if (UserState.getUser() != null) {
                    HappyPetApplication.get().getMoccaApi()
                            .getMainFriendData(start, size, new IRequest<MainZuixinData>() {

                                @Override
                                public void request(MainZuixinData t) {

                                    iLoadNextPageData.loadNextPageData(t == null ? null : t.array);
                                }

                            });
                } else {
                    nologin.setVisibility(View.VISIBLE);
                }
            }

        }



        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                final MainZuixinData.MainTiezi value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();

            if (holder == null) {
                holder = new ViewHolder();
                holder.line = convertView.findViewById(R.id.line);
                holder.layout_imgs = (LinearLayout) convertView.findViewById(R.id.layout_imgs);
                holder.lay_zan = (RelativeLayout) convertView.findViewById(R.id.lay_zan);
                holder.layout_gozan = (RelativeLayout) convertView.findViewById(R.id.layout_gozan);
                holder.layout_gohuifu =
                        (RelativeLayout) convertView.findViewById(R.id.layout_gohuifu);
                holder.iv_icon = (CircleImageView) convertView.findViewById(R.id.iv_icon);
                holder.iv_zan = (ImageView) convertView.findViewById(R.id.iv_zan);
                holder.iv_jing = (ImageView) convertView.findViewById(R.id.iv_jing);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                holder.tv_position = (TextView) convertView.findViewById(R.id.tv_position);
                holder.tv_zancount = (TextView) convertView.findViewById(R.id.tv_zancount);
                holder.tv_huifucount = (TextView) convertView.findViewById(R.id.tv_huifucount);
                holder.tv_viewcount = (TextView) convertView.findViewById(R.id.tv_viewcount);
                holder.tv_zanname1 = (TextView) convertView.findViewById(R.id.tv_zanname1);
                holder.tv_zanname2 = (TextView) convertView.findViewById(R.id.tv_zanname2);
                holder.tv_zanguo = (TextView) convertView.findViewById(R.id.tv_zanguo);
                convertView.setTag(holder);
            }

            map.put(position, holder.iv_zan);


            this.selectedposition1 = position;
            // this.value1 = value;
            // this.holder1 = holder;

            if (value != null
                    && Integer.parseInt(TextUtils.isEmpty(value.recommend_add) ? "0"
                            : value.recommend_add) > 0) {
                holder.tv_zancount.setText(value.recommend_add);
            } else {
                holder.tv_zancount.setText("赞");
            }
            // if (Integer.parseInt(value.replies) > 0) {
            holder.tv_huifucount.setText(value.replies);
            holder.tv_viewcount.setText(value.views);
            // } else {
            // holder.tv_huifucount.setText("");
            // }

            ImageLoader.getInstance().displayImage(value.userface, holder.iv_icon,
                    BitmapUtil.getMyCustomLoading());

            holder.tv_name.setText(value.author);
            holder.tv_time.setText(CommonUtil.formatTimeForListCommon(value.updatetime));

            if (!value.subject.equals("")) {
                holder.tv_title.setVisibility(View.VISIBLE);
                holder.tv_title.setText(CommonUtil.convetToHtml(
                        CommonUtil.parseEmoji(value.subject), mContext));
            } else {
                holder.tv_title.setVisibility(View.GONE);
            }

            if (!value.message.equals("")) {
                holder.tv_content.setVisibility(View.VISIBLE);
                holder.tv_content.setText(CommonUtil.convetToHtml(
                        CommonUtil.parseEmoji(value.message), mContext));
            } else {
                holder.tv_content.setVisibility(View.GONE);
            }

            if (Integer.parseInt(value.digest) > 0) {
                holder.iv_jing.setVisibility(View.VISIBLE);
            } else {
                holder.iv_jing.setVisibility(View.GONE);
            }

            if (value.recommendmy.equals("1")) {
                isZanMap.put(position, true);
                holder.iv_zan.setImageResource(R.drawable.icon_hand_frs_click);
            } else {
                isZanMap.put(position, false);
                holder.iv_zan.setImageResource(R.drawable.icon_hand_frs_normal);
            }

            if (value.forumname.length() != 0) {
                holder.tv_position.setText(value.forumname);
            }

            // Integer.parseInt(value.recommendtotal) > 0 &&
            if (value.recommendarray.size() > 0) {
                holder.line.setVisibility(View.VISIBLE);
                holder.lay_zan.setVisibility(View.VISIBLE);
                if (value.recommendarray.size() >= 2) {
                    holder.tv_zanname1.setText(value.recommendarray.get(0).username + "、");
                    holder.tv_zanname2.setText(value.recommendarray.get(1).username);
                    holder.tv_zanguo.setText("等" + value.recommendtotal + "人赞过");
                } else {
                    holder.tv_zanname1.setText(value.recommendarray.get(0).username);
                    holder.tv_zanname2.setText("");
                    holder.tv_zanguo.setText("赞过");
                }
            } else {
                holder.line.setVisibility(View.GONE);
                holder.lay_zan.setVisibility(View.GONE);
            }


            // 视频或者图片
            if (holder.layout_imgs != null) {
                holder.layout_imgs.removeAllViews();
            }
            holder.layout_imgs.setVisibility(View.GONE);
            if (value.isvideo != null && value.isvideo.equals("1")) {
                isImgsMap.put(position, false);
                holder.layout_imgs.setVisibility(View.VISIBLE);
                View sView = View.inflate(mContext, R.layout.image_pet_icon_shipinzuixin, null);
                ImageView iv = (ImageView) sView.findViewById(R.id.pet_icon);
                android.view.ViewGroup.LayoutParams lp1 = iv.getLayoutParams();
                TextView community_title = (TextView) sView.findViewById(R.id.community_title);
                lp1.width = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                lp1.height = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                iv.setScaleType(ScaleType.CENTER_CROP);
                iv.setLayoutParams(lp1);

                if (CommonParameter.isLoadImg) {
                    ImageLoader.getInstance().displayImage(value.videocover, iv);
                } else {
                    iv.setImageResource(R.drawable.picture_loading);
                }
                // community_title.setVisibility(View.VISIBLE);
                // community_title.setText(ParseMsgUtil.convetToHtml(
                // CommonUtil.parseEmoji(value.subject), mContext));


                LayoutParams lp =
                        new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                sView.setLayoutParams(lp);
                holder.layout_imgs.addView(sView);
            } else if (value.isvideo == null || value.isvideo.equals("0")) {
                if (value.pics.size() > 0) {
                    holder.layout_imgs.setVisibility(View.VISIBLE);
                    isImgsMap.put(position, true);
                }
                for (int i = 0; i < value.pics.size(); i++) {
                    final int j = i;
                    // LinearLayout view1 =
                    // (LinearLayout) View.inflate(mContext, R.layout.image_pet_icon_zuixin,
                    // null);
                    LinearLayout view1 =
                            (LinearLayout) LayoutInflater.from(mContext).inflate(
                                    R.layout.image_pet_icon_zuixin, null);
                    LinearLayout layout_count =
                            (LinearLayout) view1.findViewById(R.id.layout_for_count);
                    TextView tv_mycount = (TextView) view1.findViewById(R.id.tv_mycount);

                    ImageView iv1 = (ImageView) view1.findViewById(R.id.pet_icon);
                    // TextView community_title = (TextView)
                    // view1.findViewById(R.id.community_title);
                    android.view.ViewGroup.LayoutParams lp2 = iv1.getLayoutParams();

                    lp2.width =
                            (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                    lp2.height =
                            (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                    iv1.setScaleType(ScaleType.CENTER_CROP);
                    iv1.setLayoutParams(lp2);
                    if (CommonParameter.isLoadImg) {
                        ImageLoader.getInstance().displayImage(value.pics.get(i).url, iv1);
                    } else {
                        iv1.setImageResource(R.drawable.picture_loading);
                    }
                    LayoutParams lp3 =
                            new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    // if (value.pics.size() == 1) {
                    // community_title.setVisibility(View.VISIBLE);
                    // community_title.setText(ParseMsgUtil.convetToHtml(
                    // CommonUtil.parseEmoji(value.subject), mContext));
                    //
                    // }

                    if (i == 2 && Integer.parseInt(value.picnum) > 3) {
                        tv_mycount.setText("共" + value.picnum + "张");
                        layout_count.setVisibility(View.VISIBLE);
                    }


                    if (i > 0) {
                        lp3.leftMargin = CommonUtil.dip2px(mContext, 5);
                    }

                    view1.setLayoutParams(lp3);

                    view1.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO 到图片集
                            skipToImgs(value.pics.get(j).aid, value.tid);
                        }


                    });
                    holder.layout_imgs.addView(view1);

                }
            }



            final OnClickListener itemClickListener = new OnClickListener() {

                @Override
                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    switch (view.getId()) {
                        case R.id.iv_icon:
                        case R.id.tv_name:
                        case R.id.tv_time:
                            // 进入他人中心

                            goOthersCenter(value.authorid, value.author, value.userface);
                            break;

                        case R.id.tv_zanname1:
                            // 进入该人中心
                            if (value.recommendarray != null && value.recommendarray.size() > 0) {
                                goOthersCenter(value.recommendarray.get(0).recommenduid,
                                        value.recommendarray.get(0).username,
                                        value.recommendarray.get(0).userface);
                            }
                            break;
                        case R.id.tv_zanname2:
                            // 进入该人中心
                            if (value.recommendarray != null && value.recommendarray.size() > 1) {
                                goOthersCenter(value.recommendarray.get(1).recommenduid,
                                        value.recommendarray.get(1).username,
                                        value.recommendarray.get(1).userface);
                            }
                            break;
                        case R.id.layout_gohuifu:
                            // 回复
                            // 进入展示图片切换
                            Toast.makeText(mContext, "进入回复!", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.layout_gozan:
                        case R.id.tv_zancount:
                        case R.id.iv_zan:
                            // 点赞
                            goZan(position, value);

                            break;
                        case R.id.lay_zan:
                            // 进入点赞列表
                            Intent i = new Intent(mContext, ZanListActivity.class);
                            i.putExtra("title", value.subject);
                            i.putExtra("tid", value.tid);
                            i.putExtra("totalzan", Integer.parseInt(value.recommend_add));
                            startActivity(i);
                            break;

                        default:
                            break;
                    }

                }

                private void goOthersCenter(String uid, String name, String userface) {
                    // TODO Auto-generated method stub
                    // 进入他人中心
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.activity.MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            UserInfoFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.KEY_UID, uid);
                    bundle.putString(Constants.KEY_USERNAME, name);
                    bundle.putString(Constants.KEY_USERFACE, userface);
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    getActivity().startActivity(intent);
                }
            };

            OnClickListener videoClickListener = new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO 处理视频点击
                    Toast.makeText(mContext, "进入视频 !", Toast.LENGTH_SHORT).show();
                }
            };
            // 进入赞列表
            holder.lay_zan.setOnClickListener(itemClickListener);
            // 进入个人中心
            holder.iv_icon.setOnClickListener(itemClickListener);
            holder.tv_name.setOnClickListener(itemClickListener);
            holder.tv_time.setOnClickListener(itemClickListener);

            // holder.tv_zancount.setOnClickListener(itemClickListener);
            // holder.tv_zanname1.setOnClickListener(itemClickListener);
            // holder.tv_zanname2.setOnClickListener(itemClickListener);
            // holder.tv_zanguo.setOnClickListener(itemClickListener);
            // holder.layout_gohuifu.setOnClickListener(itemClickListener);
            // holder.layout_gozan.setOnClickListener(itemClickListener);

            // if (isImgsMap.containsKey(position) && isImgsMap.get(position)) {
            // holder.layout_imgs.setOnClickListener(itemClickListener);
            // } else {
            // holder.layout_imgs.setOnClickListener(null);
            // // holder.layout_imgs.setOnClickListener(videoClickListener);
            // }

            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    startActivity(intent);
                }
            });

            return convertView;
        }

        protected void skipToImgs(String aid, String tid) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(mContext, PostDetailImgsActivity.class);
            intent.putExtra(Constants.PARAM_PHOTO_POSITION, aid);
            intent.putExtra(Constants.KEY_POST_TID, tid);
            startActivity(intent);
        }

        private void goZan(final int position, final MainZuixinData.MainTiezi value) {

            if (UserState.isLogged(getActivity())) {
                if (isZanMap.get(position)) {
                    Toast.makeText(mContext, "已赞过 !", Toast.LENGTH_SHORT).show();
                } else {
                    if (CommonUtil.checkNetState(mContext)) {

                        map.get(position).setImageResource(R.drawable.icon_hand_frs_click);


                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                            final ObjectAnimator oa =
                                    ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                            "width",

                                            CommonUtil.dip2px(mContext, 0),
                                            CommonUtil.dip2px(mContext, 40));
                            final ObjectAnimator ob =
                                    ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                            "height",

                                            CommonUtil.dip2px(mContext, 0),
                                            CommonUtil.dip2px(mContext, 40));
                            oa.setInterpolator(new AccelerateDecelerateInterpolator());
                            ob.setInterpolator(new AccelerateDecelerateInterpolator());
                            oa.setDuration(250);
                            ob.setDuration(250);


                            final AnimatorSet set = new AnimatorSet();
                            set.play(oa).with(ob);

                            set.addListener(new AnimatorListener() {

                                @Override
                                public void onAnimationStart(Animator arg0) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationRepeat(Animator arg0) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationEnd(Animator arg0) {
                                    // TODO Auto-generated method stub


                                    ObjectAnimator oa2 =
                                            ObjectAnimator.ofInt(
                                                    new ViewWrapper2(map.get(position)), "width",
                                                    CommonUtil.dip2px(mContext, 40),
                                                    CommonUtil.dip2px(mContext, 25));
                                    ObjectAnimator ob2 =
                                            ObjectAnimator.ofInt(
                                                    new ViewWrapper2(map.get(position)), "height",
                                                    CommonUtil.dip2px(mContext, 40),
                                                    CommonUtil.dip2px(mContext, 25));
                                    oa2.setInterpolator(new AccelerateDecelerateInterpolator());
                                    ob2.setInterpolator(new AccelerateDecelerateInterpolator());
                                    oa2.setDuration(250);
                                    ob2.setDuration(250);

                                    AnimatorSet set2 = new AnimatorSet();
                                    set2.play(oa2).with(ob2);
                                    set2.start();

                                }

                                @Override
                                public void onAnimationCancel(Animator arg0) {
                                    // TODO Auto-generated method stub

                                }
                            });

                            set.start();
                        }


                        RequestParams params = new RequestParams();
                        params.put("tid", value.tid);
                        params.put("uid", UserState.getUserUid());
                        XDHttpClient.get(xdConfig.PRAISEPOST, params,
                                new AsyncHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(int statusCode, String content) {

                                        try {
                                            if (new JSONObject(content).getInt("result") == 0) {

                                                MainZuixinData.MainTiezi.RecommendPerson info =
                                                        new MainZuixinData().new MainTiezi().new RecommendPerson();
                                                info.username = UserState.getUser().username;
                                                info.recommenduid = UserState.getUserUid();
                                                value.recommendarray.add(0, info);
                                                value.recommendmy = "1";
                                                value.recommend_add =
                                                        String.valueOf(Integer
                                                                .parseInt(value.recommend_add) + 1);
                                                isZanMap.put(position, true);
                                                Toast.makeText(mContext, "点赞成功", Toast.LENGTH_SHORT)
                                                        .show();
                                                mAdapter.notifyDataSetChanged();
                                            } else {
                                                map.get(position).setImageResource(
                                                        R.drawable.icon_hand_frs_normal);
                                                Toast.makeText(mContext, "点赞失败", Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        } catch (JSONException e1) {
                                            e1.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Throwable arg0, String arg1) {
                                        super.onFailure(arg0, arg1);
                                        map.get(position).setImageResource(
                                                R.drawable.icon_hand_frs_normal);
                                        Toast.makeText(mContext, R.string.get_error_data,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                });
                    } else {
                        Toast.makeText(mContext, R.string.pLease_check_network, Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                }
            }

        }



        private class ViewWrapper2 {
            private final View mTarget;

            public ViewWrapper2(View target) {
                mTarget = target;
            }

            public int getWidth() {
                return mTarget.getLayoutParams().width;
            }

            public void setWidth(int width) {
                mTarget.getLayoutParams().width = width;
                mTarget.requestLayout();
            }

            public int getHeight() {
                return mTarget.getLayoutParams().height;
            }

            public void setHeight(int height) {
                mTarget.getLayoutParams().height = height;
                mTarget.requestLayout();
            }
        }


        class ViewHolder {
            View line;
            LinearLayout layout_imgs;
            RelativeLayout lay_zan, layout_gozan, layout_gohuifu;
            CircleImageView iv_icon;
            ImageView iv_zan, iv_huifu, iv_jing;
            TextView tv_name, tv_time, tv_title, tv_content, tv_position, tv_zancount,
                    tv_huifucount, tv_viewcount, tv_zanname1, tv_zanname2, tv_zanguo;
        }
    }
    class LoginSuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadDatas();
            if (!mIsZuixin) {
                nologin.setVisibility(View.GONE);
            }
        }
    }

}
